package com.lw.udpdemo;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author LW
 * @2020/9/15 20:57
 */
//不需要连接服务器
public class UDPClientDemo01 {
//    DatagramPacket  数据报包
//    DatagramSocket 数据报套接字
    public static void main(String[] args) throws Exception {
        //1.建立一个Socket连接
        DatagramSocket socket = new DatagramSocket(8000);
        
        //建个包
        String msg = "hello,server!";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9000;
        //参数： 数据/数据长度起/始/地址/端口
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
        //发送包
        socket.send(packet);

        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));

        //4.关闭流
        socket.close();

    }
}
